package com.adolph.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * 〈功能概述〉<br>
 * HttpObject：客户端和服务端通讯的数据
 * @author: wangxiangjun
 * @date: 2020-10-10 16:30
 */

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断是否是HttpRequest请求
        if(msg instanceof HttpRequest){

            //通过url过滤特殊请求
            HttpRequest httpRequest = (HttpRequest) msg;
            String url = httpRequest.getUri();

            ByteBuf content = Unpooled.copiedBuffer("123123", CharsetUtil.UTF_8);
            //构造httpResponse
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
            ctx.writeAndFlush(defaultFullHttpResponse);



        }
    }
}
